﻿#include <stdio.h>
#include <windows.h>
#include <winuser.h>
#include "Link.h"
#include "ExternVar.h"

int hex(int a);
BOOL sybcend(char ch);
void sybc(const char *argv)
{

	int i=0;
	int h=0,l=0,c;
	char a,b;
	
	if (sybcend(argv[i])) //
	{
		printf("没有找到参数![%d,%d]",h,l);
		return;
	}
	if (argv[i] == ':')//:1 开头指令支持
	{
		i++;
		if (argv[i] == '$') return;//:$ 将强制结束
		if (argv[i] != '1') i--;
	}
	if (argv[i] == '1')//1 开头指令支持
	{
		i++;
		if (sybcend(argv[i])) return;
		a=hex(argv[i]);
		i++;
		if (sybcend(argv[i])) return;
		b=hex(argv[i]);
		i++;
		if (sybcend(argv[i])) return;
		h=a*10+b;
		a=hex(argv[i]);
		i++;
		if (sybcend(argv[i])) return;
		b=hex(argv[i]);
		l=a*10+b;
		GotoHL(h,l);
		i++;
	}
	while (1)
	{
		if (sybcend(argv[i])) return;
		if (argv[i] == '$')//$XX颜色标签
		{
			i++;
			if (sybcend(argv[i])) return;
			a=hex(argv[i]);
			i++;
			if (sybcend(argv[i])) return;
			b=hex(argv[i]);
			i++;
			c=a*16+b;
			colorgb(c);
			continue ;
		}
		if (argv[i] == ';')//; 换行
		{
			i++;
			if (argv[i] == ':')//;: 结束并执行新指令
			{
				i++;
				if (sybcend(argv[i])) return;
				if (argv[i] == '$') return;//;:$ 强制结束
				i++;
				if (sybcend(argv[i])) return;
				a=hex(argv[i]);
				i++;
				if (sybcend(argv[i])) return;
				b=hex(argv[i]);
				i++;
				if (sybcend(argv[i])) return;
				h=a*10+b;
				a=hex(argv[i]);
				i++;
				if (sybcend(argv[i])) return;
				b=hex(argv[i]);
				i++;
				l=a*10+b;
				GotoHL(h,l);
				continue ;
			}
			h++;
			if (h <= 24 ) GotoHL(h,l);//只有不超过80x25范围;换行才生效
			continue ;
		}		
		printf("%c",argv[i]);
		i++;
	}
}

int hex(int a)//进制转换,将0-F的字符串转换为int
{
	int i=0;
	if (a >= '0' && a <= '9') i=a-'0';
	if (a >= 'A' && a <= 'F') i=a-'7';
	if (a >= 'a' && a <= 'f') i=a-'W';
	return i;
}

BOOL sybcend(char ch)//结束检测,0x00 0x0A 0x0D 都会结束指令串
{
	if (ch == 0) return TRUE;
	if (ch == 10) return TRUE;
	if (ch == 13) return TRUE;
	return FALSE;
}

/**
 * 修改坐标位置
 */
void GotoHL (int H, int L)
{
	COORD c ;
	c.X = L ;
	c.Y = H ;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c) ;

}

/**
 * 修改光标颜色
 */
void colorgb(int col)
{
	HANDLE hOut;
	WORD color=col;
	hOut=GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(hOut,color);
}

/**
 * 给指定区域上色
 */
void color(int H,int L,int len,int col)
{
	HANDLE hOut;
	COORD pos;
	WORD color=col;
	DWORD written;
	hOut=GetStdHandle(STD_OUTPUT_HANDLE);
	//color=FOREGROUND_RED|BACKGROUND_GREEN;
	pos.X=L;
	pos.Y=H;
	FillConsoleOutputAttribute(hOut,color,len,pos,&written);
}

/**
 *
 */
void colorrs(int H,int L,int len,int col)
{
	HANDLE hOut;
	COORD pos;
	WORD color=col;
	DWORD written;
	hOut=GetStdHandle(STD_OUTPUT_HANDLE);
	//color=FOREGROUND_RED|BACKGROUND_GREEN;
	pos.X=L;
	pos.Y=H;
	FillConsoleOutputAttribute(hOut,color,len,pos,&written);
}
